import Vue from "vue";
import Vuex from 'vuex'
import cart from "./cart";
import product from "./product";
import createPersistedState from "vuex-persistedstate"

Vue.use(Vuex)

let store = new Vuex.Store({

    //状态，组件中需要被其他组件共享使用的data属性，就放到state中
    state:{
        name:"李雷",
        age:"18",
        nickname:"小雷",
        num:30,
        products:[] 
    },

    //相当于vuex的计算属性
    getters:{
        reverseN(state){
            state.nickname="小灰灰"
            return state.nickname.split('').reverse().join('')
        }
    },

    //修改state的方式
    mutations:{
        INCREASE(state){
            state.num++
        },
        SHAN(state){
            state.num--
        },
        SET_PRO(state,payload){
            state.products=payload
        }
    },

    actions:{
        FETCH_PRO(context,payload){
            console.log(context)
            fetch("http://chst.vip/data/index.json")
            .then(body=>body.json())
            .then(res=>{
                // console.log(res)
                context.commit('SET_PRO',res.data)
            })
        }
    },

    //store模块化
    modules:{
        cart,
        product
    },
    plugins:[
        createPersistedState({
            storage:window.localStorage,
            key:'nick',
            paths:['nickname','product.products']
        })
    ]
})

export default store